<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加用户按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 列表渲染 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二三级菜单 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === '0' ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 二级菜单 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级菜单 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row.id)"
              >编辑
            </el-button>
            <el-button
              type="danger"
              @click="deleteRoles(scope.row.id)"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色界面 -->
    <el-dialog
      title="添加角色"
      @close="addRolesClosed"
      :visible.sync="addRolesVisible"
      width="50%"
    >
      <!-- 内容主体区域 -->
      <el-form :model="addRolesList" ref="addRolesRef" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="addRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色界面 -->
    <el-dialog title="修改角色" :visible.sync="editRolesVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form :model="editRolesList" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCancel">取 消</el-button>
        <el-button type="primary" @click="editSuccess">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
    >
      <!-- tree控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      //   添加角色
      addRolesList: {
        roleName: '',
        roleDesc: ''
      },
      //   添加角色显示关闭
      addRolesVisible: false,
      //   修改角色
      editRolesList: {
        roleName: '',
        roleDesc: ''
      },
      //   修改角色界面显示关闭
      editRolesVisible: false,
      // 分配权限对话框
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // tree控价的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中节点ID值数组
      defKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 角色列表获取
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) { return this.$message.error('获取角色列表失败') }
      this.rolesList = res.data
    },
    // 添加角色确定按钮
    async addRoles() {
      const { data: res } = await this.$http.post('roles', {
        roleName: this.addRolesList.roleName,
        roleDesc: this.addRolesList.roleDesc
      })
      if (res.meta.status !== 201) return this.$message.error('添加角色失败')
      this.addRolesVisible = false
      this.$message.success('添加角色成功')
      this.getRolesList()
    },
    // 添加角色窗口关闭
    addRolesClosed() {
      // this.$refs.addRolesRef.resetFields()
      // console.log(this.$refs.addRolesRef.resetFields())
      this.addRolesList.roleName = ''
      this.addRolesList.roleDesc = ''
    },
    // 编辑角色按钮
    async editRoles(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询失败')
      this.editRolesList.roleName = res.data.roleName
      this.editRolesList.roleDesc = res.data.roleDesc
      this.editRolesList.id = res.data.roleId
      this.editRolesVisible = true
    },
    // 修改角色确定按钮
    async editSuccess() {
      const { data: res } = await this.$http.put(
        `roles/${this.editRolesList.id}`,
        {
          roleName: this.editRolesList.roleName,
          roleDesc: this.editRolesList.roleDesc
        }
      )
      if (res.meta.status !== 200) return this.$message.error('编辑失败')
      this.$message.success('编辑成功')
      this.editRolesVisible = false
      this.getRolesList()
    },
    // 修改角色取消按钮
    editCancel() {
      this.editRolesVisible = false
      this.$message.warning('取消修改角色')
      this.getRolesList()
    },
    // 删除角色按钮
    async deleteRoles(id) {
      const confirmResult = await this.$confirm('确定删除该角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 确定 res 返回的是 confirm
      // 取消 res 返回的是 cancel
      if (confirmResult === 'cancel') return this.$message.info('取消删除角色')
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getRolesList()
      this.$message.success('成功删除角色')
    },
    // 所有菜单的×
    async removeRightById(role, rightID) {
      const confirmResult = await this.$confirm('删除确认', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除!')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightID}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // this.getRolesList()
      role.children = res.data
    },
    // 分配权限按钮
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) { return this.$message.error('获取权限数据失败') }
      this.rightsList = res.data
      // console.log(this.rightsList)
      this.defKeys = []
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归获取角色下所有三级权限的id，并保存到defKeys中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keyStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: keyStr
        }
      )
      if (res.meta.status !== 200) return this.$message.error('分配失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
